package tech.summerly.weather.data.remote

import com.jakewharton.retrofit2.adapter.kotlin.coroutines.experimental.CoroutineCallAdapterFactory
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import tech.summerly.weather.model.Region
import tech.summerly.weather.util.Position

/**
 * 高德地图 api 服务
 */
object AmapService {

    private val api: AmapServiceApi = Retrofit.Builder()
            .baseUrl("http://restapi.amap.com/v3/")
            .callFactory(OkHttpClient.Builder().addInterceptor(HttpLoggingInterceptor()).build())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(CoroutineCallAdapterFactory())
            .build()
            .create(AmapServiceApi::class.java)


    suspend fun getRegionByPosition(position: Position): String {
        val region = api.region(position.stringify()).await()
        val status = region["status"].asInt
        if (status == 0) {
            throw Exception(region["info"].asString)
        }
        val addressComponent = region["regeocode"].asJsonObject["addressComponent"].asJsonObject
        val district = addressComponent["district"].asString
        val township = addressComponent["township"].asString
        return district + township
    }

    suspend fun getRegionByPosition1(position: Position): Region {
        val result = api.region(position.stringify()).await()
        val status = result["status"].asInt
        if (status == 0) {
            throw Exception(result["info"].asString)
        }
        val regeo = result["regeocode"].asJsonObject
        val addressComponent = regeo["addressComponent"].asJsonObject

        val fullAddress = regeo["formatted_address"].asString
        val province = addressComponent["province"].asString


        //因为cityName服务端返回的值不正常
        val cityObject = addressComponent["city"]
        val cityName = if (cityObject.isJsonArray && cityObject.asJsonArray.size() == 0) {
            province
        } else {
            cityObject.asString
        }
        val district = addressComponent["district"].asString
        val township = addressComponent["township"].asString

        return Region(
                fullName = fullAddress,
                name = district + township,
                position = position,
                province = province,
                city = cityName)
    }
}